package com.shujia.flink.tf;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import javax.xml.crypto.Data;

public class Demo6Window {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<String> linesDS = env.socketTextStream("master", 8888);

        DataStream<Tuple2<String, Integer>> kvDS = linesDS
                //一行转换成多行，返回kv格式
                .flatMap((line, out) -> {
                    for (String word : line.split(",")) {
                        out.collect(Tuple2.of(word, 1));
                    }
                }, Types.TUPLE(Types.STRING, Types.INT));

        //分组
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(kv -> kv.f0);

        WindowedStream<Tuple2<String, Integer>, String, TimeWindow> windowDS = keyByDS
                //划分窗口，每隔5秒一个窗口
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)));

        DataStream<Tuple2<String, Integer>> countDS = windowDS.sum(1);

        countDS.print();

        env.execute();


    }
}
